<?php
/**
 * IG_Product 服务器
 *
 * @author mmxie
 * @copyright Copyright (c) 2009 Green Shore (http://www.iwgame.com)
 * @version $Id: Product.php 1082 2011-12-09 09:27:48Z mmxie $
 */
class IG_Product
{
    /**
     * @var IG_Product
     */
    private static $_instance = null;

    protected $_product = array();

    /**
     *
     * @return IG_Product
     */
    public static function getInstance()
    {
        if (self::$_instance == null) {
            self::$_instance = new self();
        }
        return self::$_instance;
    }

    public function __construct()
    {
        $cache = Zend_Registry::get('lvan_cache');
        $arkAPI = Zend_Registry::get('lvan_options')->arkAPI;

        if (!($data = $cache->load(__CLASS__))) {
            $data = array();
            $params = array(
                'tag'  => 'product,game-area,game-group',
                'type' => 'config_app',
            );

            $data = Zend_Json::decode(
                file_get_contents($arkAPI . '?' . http_build_query($params))
            );

            if ($data[2]['name'] == 'P-WG1') {
                $data[2]['children'] = array(
                    array(
                        'name'     => 'WG1-AREA1',
                        'title'    => '石器部落',
                        'tags'     => 'game-area',
                        'children' => $data[2]['children'],
                        'data'     => null
                    )
                );
            } else {
                throw new IG_Exception('区组信息更新错误, 无法定位P-WG1');
            }
            $cache->save($data, __CLASS__);



            $frontCacheDir = APPLICATION_PATH . '/../public/cache/';
            file_put_contents(
                $frontCacheDir . '/config.json',
                Zend_Json::encode($data)
            );
            foreach ($data as $product) {
                file_put_contents(
                    $frontCacheDir . $product['name'] . '.config.json',
                    isset($product['children']) ? json_encode($product['children']) : null
                );
            }
        }

        foreach ($data as $product) {
            $this->_products[$product['name']] = new IG_Product_Config_Product($product);
        }
    }

    /**
     *
     * @param string $name
     * @return IG_Product_Config_Product
     */
    public function getProduct($name = PRODUCT)
    {
        return isset($this->_products[$name]) ? $this->_products[$name] :
               new IG_Product_Config_Product();
    }

    public function getProducts()
    {
        return $this->_products;
    }
}